package top.csy8888.ch02.common;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;

import java.io.InputStream;

/**
 * @author CSY
 * @date 2025 - 09 - 04
 */
public class MinioOptions {
    private MinioClient client;
    private String bucketName;

    public MinioOptions(MinioClient client, String bucketName) {
        this.client = client;
        this.bucketName = bucketName;
        initBucket();
    }

    public void upload(String path, String contentType, long size, InputStream input){
        try {
            client.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(path)
                    .contentType(contentType)
                    .stream(input,size,-1).build());
        } catch (Exception e) {
            throw new RuntimeException("upload fail:"+e);
        }
    }

    protected void initBucket(){
        try {
            if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())){
                client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            throw new RuntimeException("create fail:"+e);
        }
    }
}
